<template>
  <!--  :scroll="{ y: scrollY }"-->
  <a-table :columns="columns"
           :ref="handleRef"
           class="baseTable"
           size="small"
           :data-source="props.dataSource"
           :loading="loading"
           :pagination="showPagination ? {...pagination,...paginationOptions} : false"
           :rowClassName="(___record:any, index:any) => (index % 2 === 1 ? 'table-striped' : null)"
           :row-key="(record:any) => `${record[rowKey || '']}`"
           :row-selection="isSelect ? {...rowSelectionOptions,...{ selectedRowKeys: selectedRowKeys, onChange: onRowSel,}} : null"
           :scroll="{ x: props.scrollX || 'max-content'}"
           @change="handleTableChange"
  >
    <template #expand="record">
      <slot name="expand" :record="record" />
    </template>
    <template v-slot:[item]="scope" v-for="item in renderArr">
      <template v-if="scope.column.editType">
        <template v-if="scope.column.editType === 'input'">
          <a-input v-if="scope.record.isEdit"
                   v-model:value="scope.record[scope.column.dataIndex]" />
          <slot v-else :name="item" :scope="scope" v-bind="scope || {}"></slot>
        </template>
        <template v-else-if="scope.column.editType === 'image'">
          <upload-image
              v-if="scope.record.isEdit"
              :max-size="2"
              v-model:value="scope.record[scope.column.dataIndex]"
              :max-length="1"
              type="png,jpg"
              :placeholder="scope.column.title" />
          <a-image
              v-else
              width="90px"
              height="90px"
              :src="scope.record[scope.column.dataIndex][0]?.url || scope.record[scope.column.dataIndex][0]?.thumbUrl"
          >
          </a-image>
        </template>
      </template>
      <!-- // 插槽后面-slot:[item] 如果是动态渲染插槽需要使用这种方式
         //renderArr 是父组件传递过来的用了插槽的名字,等下会在父组件中讲清楚,通过这个数组来遍历生成插槽 -->
      <!-- //再通过这个插槽传递数据给父组件,做一些编辑提交的操作等等 -->
      <slot v-else :name="item" :scope="scope" v-bind="scope || {}"></slot>
    </template>
    <template #footer v-if="showAddButton">
      <a-button class="add-row-button" block type="dashed" :icon="h(PlusOutlined)" @click="addRow"> 添加一行</a-button>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, useSlots, toRef, toRefs, shallowRef, h} from 'vue';
import {Column, Pagination} from "./baseTableInterface.ts";
import {getTableScroll} from "../utils.ts";
import uploadImage from '../upload/uploadImage.vue'
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  columns: {
    type: Array as () => Column[],
    required: true,
  },
  scrollX: {
    type: [Number, String],
    required: false,
  },
  scrollY: {
    type: [Number, String],
    required: false,
  },
  dataSource: {
    type: Array as () => any[],
    required: true,
  },
  isSelect: {
    type: Boolean,
    required: true,
  },
  selectType: {
    type: String,
    required: false,
    default: 'checkbox' // 多选/单选，checkbox or radio
  },
  rowKey: {
    type: String,
    required: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  pagination: {
    type: Object as () => Pagination | null,
    default: null,
  },
  showPagination: {
    type: Boolean,
    default: true,
  },
  preserveSelectedRowKeys: { // 允许翻页后记录所选数据
    type: Boolean,
    default: false,
  },
  // 显示添加表格内容按钮
  showAddButton: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['change','onSelRowKeys','addRow']);

const loading = toRef(props,'loading')
const pagination = props.pagination;
const paginationOptions = {
  showTotal: () => `共 ${props.pagination?.total} 条数据`,
  showQuickJumper: true
}
const slots = useSlots();
const scrollX = ref()
const scrollY = ref()
const tableRef = shallowRef(null)

const rowSelectionOptions = ref({
  type: props.selectType,
  preserveSelectedRowKeys: props.preserveSelectedRowKeys

})

const dataSource = reactive(props.dataSource)
const state = reactive({
  selectedRowKeys: [] as (string | number)[],
});

//@ts-ignore
const onRowSel = (selectedRowKeys: (string | number)[], _selectedRows:any) => {
  state.selectedRowKeys = selectedRowKeys;
  emit("onSelRowKeys", selectedRowKeys, _selectedRows)
};
// 赋值动态ref到变量
const handleRef = (el: any) => {
  if (el) {
    tableRef.value = el
  }
}

const renderArr = Object.keys(slots);

function addRow(){
  const tempObj:any = {}
  props.columns?.forEach((item:Column)=>{ tempObj[item.key] = ''})
  tempObj['isEdit'] = true
  emit('addRow',tempObj)
}

const handleTableChange = (pagination: Pagination, filters: any, sorter: any) => {
  emit('change', pagination, filters, sorter);
};

onMounted(() => {
  // loading.value = false;
  scrollY.value = getTableScroll()
});

const { selectedRowKeys } = toRefs(state);

const cancelSelect = () => {
  state.selectedRowKeys = []
}

defineExpose({
  cancelSelect
})

</script>
<style scoped lang="scss">
:deep .ant-table-footer{
  text-align: center;
}
.baseTable{
  height: 100%;
  padding: 16px;
  background: #ffffff;
}
.add-row-button{
  max-width: 600px;
  margin: 0 auto;
}
</style>

